<?php

namespace common\models;

use Yii;
use yii\db\ActiveQuery;
use yii\db\ActiveRecord;

/**
 * 城市类，包含省市区等数据
 *
 * @property integer $id
 * @property string $division_name
 * @property string $pinyin
 * @property string $division_type
 * @property integer $parent_id
 * @property integer $xingzhengdaima
 * @property integer $show_order
 * @property integer $status
 * @property integer $update_time
 * @property string $alias
 * @property integer $create_time
 * @property string $initials
 */
class Division extends ActiveRecord
{

    /**
     *
     * @var array 城市的下属节点
     */
    public $childs = [];

    /**
     *
     * @var type id为key的全部城市数组
     */
    public static $allcity = array();

    const PROVICE_TYPE = 0;
    const CITY_TYPE = 1;
    const DISRUCT_TYPE = 2;

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'zs_division';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['id'], 'required'],
            [['id', 'parent_id', 'xingzhengdaima', 'show_order', 'status', 'update_time', 'create_time'], 'integer'],
            [['division_type'], 'string'],
            [['division_name', 'alias'], 'string', 'max' => 30],
            [['pinyin'], 'string', 'max' => 50],
            [['initials'], 'string', 'max' => 20]
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'division_name' => '行政区名称',
            'pinyin' => '行政区拼音',
            'division_type' => '地区类型',
            'parent_id' => '父级id',
            'xingzhengdaima' => '行政代码',
            'show_order' => '显示顺序编号',
            'status' => '当前状态;-1:作废 1:正常 2:隐藏',
            'update_time' => '最后一次更新时间,北京时间',
            'alias' => '别名',
            'create_time' => '创建时间',
            'initials' => '首字母拼音缩写',
        ];
    }

    /**
     * 返回id为key的所有城市数据
     * 
     * @return array
     */
    public static function getAllCity()
    {
        // 查询缓存
        if (empty(self::$allcity)) {
            self::$allcity = Yii::$app->cache->get('allcity');
        }
        // 查询数据库
        if (empty(self::$allcity)) {
            $allcity = self::find()->all();
            foreach ($allcity as $city) {
                self::$allcity[$city->id] = $city;
            }
            Yii::$app->cache->set('allcity', self::$allcity, 86400 * 3);
        }
        return self::$allcity;
    }

    /**
     * 根据城市ID获取城市信息
     * @param int $id 城市ID
     * @return \common\models\Division 返回Division的实例
     */
    public static function getCityById($id)
    {
        self::getAllCity();
        // 判断城市是否存在
        if (!isset(self::$allcity[$id])) {
            return null;
        }
        // 返回城市的实例
        return self::$allcity[$id];
    }

    /**
     * 根据城市ID获取城市名称
     * @param int $id 城市ID
     * @return string 如果无法查询到城市，则返回空；否则返回城市名称
     */
    public static function getCitynameById($id)
    {
        $city = self::getCityById($id);
        if ($city instanceof self) {
            return $city->division_name;
        }
        return '';
    }

    /**
     * 获取省市县三级结构的城市数据
     */
    public static function getCityList()
    {
        $cachedData = Yii::$app->cache->get('allcity_pcd_list');
        if (!empty($cachedData)) {
            return $cachedData;
        }
        $allCity = self::getAllCity();
        $provinces = [];
        $newProvinces = [];
        $cities = [];
        foreach ($allCity as $c) {
            if (isset($cities[$c->id])) {
                $childs = $cities[$c->id]['childs'];
                $cities[$c->id] = $c->attributes;
                $cities[$c->id]['childs'] = $childs;
            } else {
                $cities[$c->id] = $c->attributes;
                $cities[$c->id]['childs'] = [];
            }
            if ($c->parent_id == 0) {
                if (!isset($provinces[$c->id])) {
                    $provinces[$c->id] = $cities[$c->id];
                } else {
                    $childs = $provinces[$c->id]['childs'];
                    $provinces[$c->id] = $cities[$c->id];
                    $provinces[$c->id]['childs'] = $childs;
                }
                continue;
            }
            if (!isset($cities[$c->parent_id])) {
                $cities[$c->parent_id] = [];
                if ($c->division_type == 'city') {
                    $provinces[$c->parent_id] = ['childs' => []];
                }
            }
            $cities[$c->parent_id]['childs'][] = $c->attributes;
            if ($c->division_type == 'city') {
                $provinces[$c->parent_id]['childs'][] = $c->id;
            }
        }
        foreach ($provinces as $province) {
            $childs = [];
            foreach ($province['childs'] as $cityId) {
                $childs[] = $cities[$cityId];
            }
            $newProvince = $province;
            unset($newProvince['childs']);
            $newProvince['childs'] = $childs;
            $newProvinces[] = $newProvince;
            unset($childs);
            unset($newProvince);
        }
        Yii::$app->cache->set('allcity_pcd_list', $newProvinces, 86400 * 3);
        return $newProvinces;
    }

    /**
     * 
     * @param type $parentId
     * @return string
     */
    public static function getProvice($parentId)
    {

        $provive = Yii::$app->cache->get('bprovice');
        if (!empty($provive)) {
            return $provive;
        }
        $dataProvider = self::getCityInfo($parentId);
        if (empty($dataProvider->getCount())) {
            return '';
        }
        $data = ['total_count' => 0, 'list' => []];
        $cityInfo = $dataProvider->getModels();
        foreach ($cityInfo as $val) {
            $data['list'][] = [
                'id' => $val->id,
                'name' => $val->division_name
            ];
        }
        $data['total_count'] = $dataProvider->getCount();
        Yii::$app->cache->set('bprovice', $data, 86400 * 3);
        return $data;
    }

    public static function getProvinceByPid($province_id)
    {
        $a_city = self::getCityList();

        foreach($a_city as $value){
            if($value['id'] == $province_id){
                return $value;
            }
        }

    }

    /**
     * 根据省id获取城市信息
     * @param type $parentId
     * @return string
     */
    public static function getCity($parentId)
    {

        $provive = Yii::$app->cache->get('bcity' . $parentId);
        if (!empty($provive)) {
            return $provive;
        }
        $dataProvider = self::getCityInfo($parentId);
        if (empty($dataProvider->getCount())) {
            return '';
        }
        $data = ['total_count' => 0, 'list' => []];
        $cityInfo = $dataProvider->getModels();
        foreach ($cityInfo as $val) {
            $data['list'][] = [
                'id' => $val->id,
                'name' => $val->division_name
            ];
        }
        $data['total_count'] = $dataProvider->getCount();
        Yii::$app->cache->set('bcity' . $parentId, $data, 86400 * 3);
        return $data;
    }

    /**
     * 更具cityId获取地区信息
     * @param type $parentId
     * @return string
     */
    public static function getDisruct($parentId)
    {

        $provive = Yii::$app->cache->get('bdisruct' . $parentId);
        if (!empty($provive)) {
            return $provive;
        }
        $dataProvider = self::getCityInfo($parentId);
        if (empty($dataProvider->getCount())) {
            return '';
        }
        $data = ['total_count' => 0, 'list' => []];
        $cityInfo = $dataProvider->getModels();
        foreach ($cityInfo as $val) {
            $data['list'][] = [
                'id' => $val->id,
                'name' => $val->division_name
            ];
        }
        $data['total_count'] = $dataProvider->getCount();
        Yii::$app->cache->set('bdisruct' . $parentId, $data, 86400 * 3);
        return $data;
    }

    public static function getCityInfo($parentId)
    {
        $query = self::find()->where(['parent_id' => $parentId])->orderBy(['pinyin' => SORT_ASC]);
        $dataProvider = new \yii\data\ActiveDataProvider([
            'query' => $query,
            'pagination' => ['pageSize' => 200, 'page' => 0]
        ]);
        return $dataProvider;
    }
    /**
     * 更具县区的名字 获取city provice district id
     * @param type $city
     * @param type $type
     * @return string
     */
    public static function getDivisionIdByCityNameAndType($city, $type = 'district')
    {
        $city = self::find()->where('division_name=:division_name and division_type=:division_type', [':division_name' => $city, ':division_type' => $type])->with('division')->one();
        $arr_city = [];
        if (!empty($city)) {
            $arr_city['cid'] = $city->parent_id;
            $arr_city['did'] = $city->id;
            if (!empty($city->division)) {
                $arr_city['pid'] = $city->division->parent_id;
            } else {
                $arr_city['pid'] = '';
            }
        }
        return $arr_city;
    }

    public function getDivision()
    {
        return $this->hasOne(Division::className(), ['id' => 'parent_id']);
    }

    public static function getProvinceCity()
    {

        $all_city = self::getCityList();
        $result = [];
        foreach($all_city as  $province) {
            $result[$province['id']]['name'] = $province['division_name'];
            foreach($province['childs'] as $city){
                $result[$province['id']]['child'][$city['id']] = $city['division_name'];
            }
        }
        return $result;
    }

}
